//
//  QRCodeMyCardViewController.swift
//  Weibo
//
//  Created by 杨雨哲 on 15/7/1.
//  Copyright © 2015年 yyz. All rights reserved.
//
import UIKit
import FFAutoLayout

class QRCodeMyCardViewController: UIViewController {

    lazy var iconView:UIImageView  = UIImageView()
    
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        view.addSubview(iconView)
        iconView.ff_AlignInner(ff_AlignType.CenterCenter, referView: view, size: CGSize(width: 200, height: 200))
        iconView.backgroundColor = UIColor.lightGrayColor()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        iconView.image = generateQRCodeImage()
    }
    
    private func generateQRCodeImage() -> UIImage {
        
        // 1. 建立二维码滤镜
        let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
        
        // 2. 设置成初始值
        qrFilter.setDefaults()
        
        // 3. 通过 KVC 设置滤镜信息
        qrFilter.setValue("coderY2015".dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
        
        // 4. 获取结果
        let ciImage = qrFilter.outputImage
        
        // 5. 生成图片的大小  23 * 23
        print(ciImage.extent)
        
        // 6 放大图片
        let transform = CGAffineTransformMakeScale(15, 15)
        let transformImage = ciImage.imageByApplyingTransform(transform)
        
        // 7. 颜色滤镜
        let colorFilter = CIFilter(name: "CIFalseColor")!
        colorFilter.setDefaults()
        colorFilter.setValue(transformImage, forKey: "inputImage")
       
        // 前景色
        colorFilter.setValue(CIColor(color:UIColor.blackColor()), forKey: "inputColor0")
        // 背景色
        colorFilter.setValue(CIColor(color:UIColor.whiteColor()), forKey: "inputColor1")
        
        let resultImage = colorFilter.outputImage
        let avatar = UIImage(named: "avatar")!
        return insertAvatarImage(UIImage(CIImage: resultImage), avatar: avatar)
    
    }
    
    private func insertAvatarImage(image:UIImage, avatar:UIImage) -> UIImage{
        
        // 1. 开启绘图上下文，和二维码图像相同大小
        UIGraphicsBeginImageContext(image.size)
        
        // 2. 绘图
        let rect = CGRect(origin: CGPointZero, size: image.size)
        image.drawInRect(rect)
        
        // 添加头像
        let w = rect.width * 0.25
        let x = (rect.width - w) * 0.5
        let y = (rect.height - w) * 0.5
        avatar.drawInRect(CGRect(x: x, y: y, width: w, height: w))
        
        // 3. 取得结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        
        // 4. 关闭上下文
        UIGraphicsEndImageContext()
        
        // 5. 返回结果
        return result
    }
    
}
